﻿using NHibernate;

namespace Sebrae.Academico.InfraEstrutura.Core.UnitOfWork
{
    public sealed class UnitOfWork : INHibernateUnitOfWork
    {
        private ISession context;

        public ISession Context
        {
            get { return SessionManager.Instance.Session; }
            // .SessionFactory.GetCurrentSession(); }
        }

        public UnitOfWork()
        {
            this.context = SessionManager.Instance.OpenSession();
        }

        public void Commit()
        {
            this.context.Transaction.Commit();
        }

        public void Rollback()
        {
            if (this.context.Transaction.IsActive)
                this.context.Transaction.Rollback();
        }

        public void Dispose()
        {
            if (this.context.IsConnected && this.context.IsOpen)
                this.context.Close();
            //Todo: rever isso
            //ISession session = CurrentSessionContext.Unbind(StaticSessionManager.SessionFactory);
            // ISession session = CurrentSessionContext.Unbind(StaticSessionManager.SessionFactory);
            //   session.Close();
        }

        //public ISession Session
        //{
        //    get { throw new NotImplementedException(); }
        //}


        public void IniciarTransacao()
        {
            if (!this.context.Transaction.IsActive && this.context.IsOpen)
                this.context.BeginTransaction();
            //throw new NotImplementedException();
        }
    }
}
